package com.victor.controller;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.Log;
import com.victor.entity.User;
import com.victor.entity.UserAddKey;
import com.victor.service.LogService;
import com.victor.service.RegisteruserService;
import com.victor.utils.DateUtils;
import com.victor.utils.Msg;

/**
 * 注册用户管理
 * 
 * @author Mr.Zhang
 *
 */
@RestController
@RequestMapping("/ruser")
public class RegisteruserController {

	@Autowired
	private RegisteruserService service;

	@Autowired
	private LogService logservice;

	// 获取注册用户列表（frozen传0是查询正常列表 1是查询已冻结列表）注册时间筛选（选择时间）
	@RequestMapping("/getRegisterusers")
	public Msg getRegisterusers(String frozen, String ruStarttime, String ruEndtime) {
		List<User> users = service.getRegisterusers(frozen, ruStarttime, ruEndtime);
		return Msg.success().add("users", users);
	}

	// 批量冻结
	// frozen_title;// 冻结原由标题
	// frozen_details;// 冻结原由详情
	// frozen_starttime;//冻结开始时间
	// frozen_endtime;//冻结结束时间
	// frozen_cycle;// 冻结周期 0.终身冻结 1.1小时, 2.1天, 3.一周, 4.一个月,5.一年,6.二年,7.三年,
	@RequestMapping("/batchFrozen")
	public Msg batchFrozen(int[] userids, String adminid, String frozen_cycle, String frozen_starttime,
			String frozen_endtime, String frozen_title, String frozen_details) {

		boolean updResult = service.batchFrozen(userids, frozen_cycle, frozen_starttime, frozen_endtime, frozen_title, frozen_details);
		if (updResult) {

			// 添加操作日志
			Log log = new Log();
			log.setDate(DateUtils.getNowDate());
			log.setTime(DateUtils.getNowTime());
			log.setAdminid(adminid);
			log.setContent("批量冻结用户");
			logservice.addLog(log);

			return Msg.success();
		}
		return Msg.fail();
	}

	// 用户详情
	@RequestMapping("getUserXQ")
	public Msg getUserXQ(Integer userid) {
		User user = service.getUserByid(userid);
		
		List<UserAddKey> userAddKeys = service.getUserAddKey();

		Map<String, Object> user_add_map = service.getUserAddByuserid(userid);

		user.setUserAdd(user_add_map);

		if (user != null) {
			return Msg.success().add("user", user).add("userAddKeys", userAddKeys);
		}
		return Msg.fail();
	}

	// 批量导出 注册用户（选择时间） 添加操作日志
	@RequestMapping("batchExport")
	public void batchExport(String adminid, String flag, String ruStarttime, String ruEndtime,
			HttpServletResponse response, HttpServletRequest request) throws Exception {
		// 数据库查询数据 exportlist 需要导出的list
		List<User> users = service.getRegisterusers(flag, ruStarttime, ruEndtime);

		// 创建poi导出数据对象
		SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
		// 创建sheet页
		Sheet sheet = sxssfWorkbook.createSheet("注册用户列表");

		CellRangeAddress region1 = new CellRangeAddress(0, 1, (short) 0, (short) 6);
		// 参数1：起始行 参数2：终止行 参数3：起始列 参数4：终止列
		sheet.addMergedRegion(region1);
		Row headTitle = sheet.createRow(0);
		headTitle.createCell(0).setCellValue("注册用户列表");

		// 创建表头
		Row headRow = sheet.createRow(4);
		// 设置表头信息
		headRow.createCell(0).setCellValue("用户id编号");
		headRow.createCell(1).setCellValue("昵称");
		headRow.createCell(2).setCellValue("姓名");
		headRow.createCell(3).setCellValue("身份证");
		headRow.createCell(4).setCellValue("手机号/账号");
		headRow.createCell(5).setCellValue("密码");
		headRow.createCell(6).setCellValue("微信名");
		headRow.createCell(7).setCellValue("微信openid");
		headRow.createCell(8).setCellValue("QQ名称");
		headRow.createCell(9).setCellValue("QQid");
		headRow.createCell(10).setCellValue("银行卡号");
		headRow.createCell(11).setCellValue("注册日期");
		headRow.createCell(12).setCellValue("冻结状态");

		// 遍历上面数据库查到的数据
		for (User user : users) {
			Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
			dataRow.createCell(0).setCellValue(user.getId());
			dataRow.createCell(1).setCellValue(user.getNickname());
			dataRow.createCell(2).setCellValue(user.getName());
			dataRow.createCell(3).setCellValue(user.getIdcard());
			dataRow.createCell(4).setCellValue(user.getPhone());
			dataRow.createCell(5).setCellValue(user.getPassword());
			dataRow.createCell(6).setCellValue(user.getWechat());
			dataRow.createCell(7).setCellValue(user.getOpenid());
			dataRow.createCell(8).setCellValue(user.getQqname());
			dataRow.createCell(9).setCellValue(user.getQqopenid());
			dataRow.createCell(10).setCellValue(user.getBankcard());
			dataRow.createCell(11).setCellValue(user.getZhucedata());
			dataRow.createCell(12).setCellValue(user.getFrozen().equals("0") ? "正常" : "已冻结");

		}
		// 下载导出文件名
		String filename = "注册用户列表";
		// 设置头信息
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/vnd.ms-excel");
		// 一定要设置成xlsx格式
		response.setHeader("Content-Disposition",
				"attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
		// 创建一个输出流
		ServletOutputStream outputStream = response.getOutputStream();
		// 写入数据
		sxssfWorkbook.write(outputStream);
		// 关闭
		outputStream.close();
		sxssfWorkbook.close();

		// 添加操作日志
		Log log = new Log();
		log.setDate(DateUtils.getNowDate());
		log.setTime(DateUtils.getNowTime());
		log.setAdminid(adminid);
		log.setContent("批量导出用户");
		logservice.addLog(log);
	}
	

	// 添加字段
	@RequestMapping("/addKey")
	public Msg addKey(String key_meaning) {
		String key_name = UUID.randomUUID().toString().replaceAll("-", "");
		int i = service.addKey(key_name, key_meaning);
		if (i > 0) {
			return Msg.success();
		}
		return Msg.fail();
	}

	// 删除字段
	@RequestMapping("/delKey")
	public Msg delKey(String key_name) {
		int i = service.delKey(key_name);
		if (i > 0) {
			return Msg.success();
		}
		return Msg.fail();
	}

}
